package com.yxtbd.travel.travelvm.ui.login

import androidx.lifecycle.MutableLiveData
import com.yxtbd.travel.travelvm.base.BaseViewModle
import com.yxtbd.travel.travelvm.model.bean.ApiBaseResult
import com.yxtbd.travel.travelvm.model.bean.LoginBean
import com.yxtbd.travel.travelvm.model.repository.LoginRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * description ： 登录viewmodel
 *
 * author : taodq
 * date : 2020/3/31 9:24
 */
class LoginViewModel : BaseViewModle() {

    private val respository by lazy { LoginRepository() }
    val uiState = MutableLiveData<LoginUiModel>()

    // ViewModel 只处理视图逻辑，数据仓库 Repository 负责业务逻辑
    fun login(username: String?, password: String?) {
        launch {
            if (username.isNullOrBlank() || password.isNullOrBlank()) {
                emitUiState(
                    showError = "用户名或密码不能为空",
                    showSuccess = null
                )
                return@launch
            }
            val result = withContext(Dispatchers.IO) { respository.login(username, password) }
            if (result is ApiBaseResult.Success) {
                emitUiState(showError = null, showSuccess = result.data)
            } else if (result is ApiBaseResult.Error) {
                emitUiState(
                    showError = result.exception.message,
                    showSuccess = null
                )
            }

        }
    }

    private fun emitUiState(
        showError: String? = null,
        showSuccess: LoginBean? = null
    ) {
        uiState.value = LoginUiModel(showError, showSuccess)
    }

    data class LoginUiModel(
        val showError: String?,
        val showSuccess: LoginBean?
    )
}